package com.liang.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.liang.pojo.Role;
import com.liang.pojo.User;
import com.liang.service.role.RoleServiceImpl;
import com.liang.service.user.UserService;
import com.liang.service.user.UserServiceImpl;
import com.liang.util.Constants;
import com.liang.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//实现Servlet复用
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("savepwd")){
            this.updatePwd(req,resp);
        }else if(method.equals("pwdmodify")){
            this.pwdModify(req,resp);
        }else if(method.equals("query")){
            this.query(req,resp);
        }else if(method.equals("add")){
            try {
                this.add(req,resp);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    //修改当前用户密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");

        boolean flag = false;

        if(o!=null && newpassword!=null){
            //调用Service业务层
            UserService userService = new UserServiceImpl();
            flag = userService.updatePwd(((User)o).getId(),newpassword);
            if(flag){
                req.setAttribute("message","密码修改成功，请退出，使用新密码登录");
                //密码修改成功，移除当前Session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else{
                req.setAttribute("message","密码修改失败");
            }
        }else{
            req.setAttribute("message","新密码有问题");
        }
        req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
    }

    //验证旧密码，session中有用户的密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        //拿到前端传入的旧密码
        String oldpassword = req.getParameter("oldpassword");
        //万能Map
        Map<String, String> hashMap = new HashMap<>();

        if(o==null){//session失效
            hashMap.put("result","sessionerror");
        }else if(oldpassword==null){//输入旧密码为空
            hashMap.put("result","error");
        }else{
            //获取session中用户的旧密码
            String userPassword = ((User) o).getUserPassword();
            if(userPassword.equals(oldpassword)){
                hashMap.put("result","true");
            }else{
                hashMap.put("result","false");
            }
        }


        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            //JSONArray 阿里巴巴的JSON工具类
            writer.write(JSONArray.toJSONString(hashMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    //查询用户列表【重点、难点】
    public void query(HttpServletRequest req, HttpServletResponse resp){
        //从前端获取数据
        String queryUserName = req.getParameter("queryUserName");
        String tmp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");

        int queryUserRole = 0;//角色传参用的是int

        //获取用户列表
        //获取用户列表需要页数的参数，所以先把参数都引入，才能调用方法
        UserServiceImpl userService = new UserServiceImpl();
        List<User> userList = null;

        if(tmp!=null && !tmp.equals("")){
            queryUserRole = Integer.parseInt(tmp);
        }

        //设置页面容量：在配置文件中，方便后续修改
        int pageSize = Constants.pageSize;
        //当前页
        int currentPageNo = 1;//最开始进入，都是在首页，即第一页

        if(pageIndex!=null && !pageIndex.equals("")){
            currentPageNo = Integer.parseInt(pageIndex);
        }
        //获取用户总数
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);

        //分页支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);

        //获取角色列表
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();

        int totalPageCount = totalCount/pageSize+1;

        //返回给前端
        req.setAttribute("userList",userList);
        req.setAttribute("roleList",roleList);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);

        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    //添加用户
    public void add(HttpServletRequest req, HttpServletResponse resp)throws Exception{

        //从前端获取数据
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        //准备工作：调用业务层需要的参数
        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());

        //调用业务层
        UserServiceImpl userService = new UserServiceImpl();
        boolean flag = userService.addUser(user);

        if(flag){
            //添加成功，重定向至查询页面
            resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
        }else{
            //添加失败，请求再次转发回添加页面
            req.getRequestDispatcher("useradd.jsp").forward(req,resp);
        }

    }
}
